package com.qf.data.listener;

import cn.hutool.log.Log;
import com.qf.common.model.DeviceModelValue;
import com.qf.common.utils.JsonUtil;
import com.qf.data.service.DeviceModelValueService;
import com.qf.data.service.HeartBeatService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 接收mq队列中设备传感器上报的数据
 * @author 千锋健哥
 */
@Slf4j
@Component
public class DeviceValueListener {

    @Autowired
    private DeviceModelValueService deviceModelValueService;

    @Autowired
    private HeartBeatService heartBeatService;

    @RabbitHandler
    @RabbitListener(queues = "qf.queue.value.device")
    public void valueReciver(Channel channel, Message message, DeviceModelValue deviceModelValue) {
        try {
            log.info("接收mq的数据为:" + JsonUtil.toJsonString(deviceModelValue));
            //将传感器上报数据存储到mongodb中
            deviceModelValueService.saveDeviceModelValue(deviceModelValue);

            //调用service, 存储设备心跳数据
            heartBeatService.savePing(deviceModelValue.getProduct_key(), deviceModelValue.getDevice());

            //第一参数: 消息唯一id, 第二参数:是否开启批量处理
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
